﻿/// ---------------------------------------------------
/// main.js
/// 
/// Create on:		25/05/2556 15:13:15
/// Original author: Wirat Khongthai
/// Email: wirat.k@g-able.com 
/// ---------------------------------------------------
/// Modification histories:
/// 
/// 
/// ---------------------------------------------------
var makeWindows = function (id, mode, title, url, raw) {
    var record = '';
    var iscopy = false;
    if (mode != "Create") {
        var grid =Ext.getCmp("grd" + id);
        record = grid.selModel.getSelection()[0];
        if (record == null) {
            Ext.MessageBox.show({ title: raw.msginfotitle, msg: raw.msgselectwarning, buttons: Ext.Msg.OK, icon: Ext.Msg.INFO });
            return;
        }
    }
    
    if (mode == "Copy")
        iscopy = true;

    var obj = Ext.getCmp('WindowsAddEdit');
    if (obj)
        obj.destroy();

    var posfixtitle = raw.btnaddcaption;
    if (mode == "Update")
        posfixtitle = raw.btneditcaption;
    var config = {
        title: title + ' [' + posfixtitle+']',
        id: 'WindowsAddEdit',
        width: raw.winwidth,
        height: raw.winheight,
        renderTo: Ext.getBody(),
        minimizable: false,
        resizable: false,
        layout: 'fit',
        closeAction: "hide",
        modal:true,
        hideMode: "offsets"
        //autoLoad: {
        //    url: url,
        //    params: {
        //        title: title,
        //        record: Ext.encode(record.raw),
        //        iscopy: iscopy
        //    },
        //    showMask: true,
        //    noCache: true,
        //    maskMsg: "Loading page...",
        //    scripts: true
        //}
    };

    var w = new Ext.Window(config);
   
    var pnlContent = new Ext.panel.Panel({
        layout: 'fit',
        border: false,
        loader: {
            autoLoad: true,
            renderer: "frame",
            url: url,
            params: {
                record: Ext.encode(record.raw),
                iscopy: iscopy
            },
            loadMask: true,
            scripts: true
        }
    });
    w.add(pnlContent);
    w.show();
    w.center();

    w.on('beforehide', function () {
        var obj = Ext.getCmp('frm' + id);
        if (obj) {
            if (obj.getForm().isDirty()) {
                Ext.MessageBox.confirm(raw.msgconfirmtitle, raw.msgconfirmdatachanged,
                     function (btn) {
                         if (btn == 'no') {
                             w.suspendEvents();
                             w.hide();  // This cannot be vetoed because no events will be fired.
                             w.resumeEvents();

                             //Clear all register components
                             var dom = Ext.getCmp('WindowsAddEdit').body.dom;
                             var components = [];
                             Ext.Array.each(Ext.get(dom).query('*'), function (dom) {
                                 var cmp = Ext.getCmp(dom.id);
                                 if (cmp)
                                     cmp.destroy();
                             });
                         }
                     });
                return false; //always return false to veto the hide.
            }
        }
        //Clear all register components
        var dom = this.body.dom;
        var components = [];
        Ext.Array.each(Ext.get(dom).query('*'), function (dom) {
            var cmp = Ext.getCmp(dom.id);
            if (cmp)
                cmp.destroy();
        });
    });
};
var makeTab = function (id, url, title, raw) {
    var win,
        tab,
        hostName,
        exampleName,
        node,
        tabTip;

    if (id === "-") {
        id = Ext.id(undefined, "extnet");
        lookup[url] = id;
    }

    tabTip = url.replace(/^\//g, "");
    tabTip = tabTip.replace(/\/$/g, "");
    tabTip = tabTip.replace(/\//g, " > ");
    tabTip = tabTip.replace(/_/g, " ");

    win = new Ext.window.Window({
        id: "w" + id,
        layout: "fit",
        title: "Source Code",
        iconCls: "#PageWhiteCode",
        width: 925,
        height: 650,
        border: false,
        maximizable: true,
        constrain: true,
        closeAction: "hide",
        listeners: {
            show: {
                fn: function () {
                    var me = this,
                        height = Ext.getBody().getViewSize().height;

                    if (this.getSize().height > height) {
                        this.setHeight(height - 20)
                    }

                    App.direct.GetSourceTabs(id, url, this.nsId, {
                        eventMask: {
                            showMask: true,
                            customTarget: this.body
                        },
                        failure: function (msg, response) {
                            Ext.Msg.alert("Failure", "The error during example loading:\n" + response.responseText);
                        }
                    });
                },

                single: true
            }
        },
        buttons: [
            {
                id: "b" + id,
                text: "Download",
                iconCls: "#Compress",
                listeners: {
                    click: {
                        fn: function (el, e) {
                            App.direct.DownloadExample(url, {
                                isUpload: true,
                                formId: "downloadForm"
                            });
                        }
                    }
                }
            }
        ]
    });

    hostName = window.location.protocol + "//" + window.location.host;
    exampleName = url;
    var maintab = Ext.getCmp('ExampleTabs');
    maintab.items.each(function (item) {
        if (item.id != "Home")
            maintab.remove(item);
    });
    tab = maintab.add(new Ext.panel.Panel({
        id: id,
        layout: 'fit',
        //constrain: true,
        tbar: [{
            text: "Source Code",
            hidden: true,
            iconCls: "#PageWhiteCode",
            listeners: {
                "click": function () {
                    Ext.getCmp("w" + id).show(null);
                }
            }
        },
        {
            text: raw.btnaddcaption,
            iconCls: 'add16',
            disabled: !raw.canadd,
            listeners: {
                "click": function () {
                    makeWindows(id, "Create", title, hostName + url + "Create", raw);
                }
            }
        },
        {
            text: raw.btneditcaption,
            id:'btneditmain',
            iconCls: "edit16",
            disabled: !raw.canedit,
            handler: function () {
                makeWindows(id, "Update", title, hostName + url + "Update", raw);
            }
            //listeners: {
            //    "click": function () {
            //        makeWindows(id, "Update", title, hostName + url + "Update", raw);
            //    }
            //}
        },
         {
             text: raw.btncopycaption,
             iconCls: "copy16",
             disabled: !raw.canadd,
             listeners: {
                 "click": function () {
                     makeWindows(id, "Copy", title, hostName + url + "Update", raw);
                 }
             }
         },
         {
             text: raw.btndeletecaption,
             iconCls: "del16",
             disabled: !raw.candelete,
             listeners: {
                 "click": function () {
                     var grid =Ext.getCmp("grd" + id);
                     var selected = grid.selModel.getSelection();
                     var record = grid.selModel.getSelection()[0];
                     if (record == null) {
                         Ext.MessageBox.show({ title: raw.msginfotitle, msg: raw.msgselectwarning, buttons: Ext.Msg.OK, icon: Ext.Msg.INFO });
                         return;
                     }
                     var record = '';
                     for (var i = 0; i < selected.length; i++) {
                         if (record == '')
                             record = Ext.encode(selected[i].raw);
                         else
                             record = record + String.fromCharCode(0) + Ext.encode(selected[i].raw);
                     }
                     Ext.Msg.confirm(raw.msgconfirmtitle, raw.msgconfirmdelete, function (btn) {
                         if (btn == 'yes') {
                             Ext.Ajax.request({
                                 url: hostName + url + "Delete",
                                 cleanRequest: true,
                                 params: { record: record },
                                 success: function (result) {
                                     var obj = Ext.JSON.decode(result.responseText);
                                     if (obj.status)
                                         Ext.getCmp("grd" + id).getStore().reload();
                                     else
                                         Ext.Msg.show({ title: raw.msgerrortitle, msg: obj.message, buttons: Ext.Msg.OK, icon: Ext.Msg.ERROR });
                                 },
                                 error: function (result) {
                                     Ext.Msg.alert(raw.msgerrortitle, result);
                                 }
                             });
                         }
                     });
                 }
             }
         },
         "-",
         {
             text: raw.btnpreviewcaption,
             iconCls: "report16",
             disabled: !raw.canpreview,
             listeners: {
                 "click": function () {
                     Ext.Msg.alert('Preview');
                 }
             }
         },
           {
               text: raw.btnprocesscaption,
               iconCls: "cog16",
               disabled: !raw.canprocess,
               listeners: {
                   "click": function () {
                       Ext.Msg.confirm(raw.msgconfirmtitle, raw.msgconfirmprocess, function (btn) {
                           if (btn == 'yes') {
                               return true;
                           }
                       });
                   }
               }
           },
           "-",
            {
                text: raw.btnsearchcaption,
                id:'btnsearch',
                iconCls: "find16",
                listeners: {
                    "click": function () {
                        var value = Ext.encode(Ext.getCmp("frmSearch" + id).getForm().getValues());
                        value = value.replace(/-inputEl/g, "");
                        document.body.style.cursor = 'wait';
                        //Ext.Ajax.request({
                        //    url: hostName + url + "Search",
                        //    cleanRequest: true,
                        //    params: { record: value },
                        //    success: function (result) {
                        //        document.body.style.cursor = 'default';
                        //        var obj = Ext.JSON.decode(result.responseText);
                        //        if (obj.status)
                        //           Ext.getCmp("grd" + id).getStore().reload();
                        //        else
                        //            Ext.Msg.show({ title: raw.msginfotitle, msg: obj.message, buttons: Ext.Msg.OK, icon: Ext.Msg.INFO });
                        //    },
                        //    error: function (result) {
                        //        document.body.style.cursor = 'default';
                        //        Ext.Msg.alert(raw.msgerrortitle, result);
                        //    }
                        //});

                        Ext.getCmp("grd" + id).getStore().load({ params: { record: value }, callback: searchcallback });
                        document.body.style.cursor = 'default';
                    }
                }
            },
            {
                text: raw.btnclosecaption,
                id: 'btnclose',
                hidden:true
            },
            {
                text: raw.frmsearchtitleinfo,
                id: 'frmsearchtitleinfo',
                hidden: true
            },
             {
                 text: raw.grdcolfieldnamecaption,
                 id: 'grdcolfieldnamecaption',
                 hidden: true
             },
             {
                 text: raw.grdcolconditioncaption,
                 id: 'grdcolconditioncaption',
                 hidden: true
             },
            {
                text: raw.grdcolcriteriavaluecaption,
                id: 'grdcolcriteriavaluecaption',
                hidden: true
            },
            {
                text: raw.grdcoloperationcaption,
                id: 'grdcoloperationcaption',
                hidden: true
            },
             {
                 text: raw.operationandcaption,
                 id: 'operationandcaption',
                 hidden: true
             },
            {
                text: raw.operationorcaption,
                id: 'operationorcaption',
                hidden: true
            }
        ],
        title: title,
        tabTip: tabTip,
        hideMode: "offsets",
        autoDestroy: false,
        loader: {
            autoLoad: true,
            renderer: "frame",
            url: hostName + url,
            loadMask: true,
            scripts: true
        },
        listeners: {
            deactivate: {
                fn: function (el) {
                    if (this.sWin && this.sWin.isVisible()) {
                        this.sWin.hide();
                    }
                }
            },
            destroy: function () {
                if (this.sWin) {
                    this.sWin.close();
                    this.sWin.destroy();
                }
                //this.items.each(function (item, index, len) {
                //    this.remove(item, true);
                //    item.destroy();
                //});
            }
        },
        closable: true
    }));
    tab.on('beforeclose', function (obj) {
        this.items.each(function (item) {
            item.destroy();
        });
        var dom = Ext.getCmp(id).body.dom;
        var components = [];
        Ext.Array.each(Ext.get(dom).query('*'), function (dom) {
            var cmp = Ext.getCmp(dom.id);
            if (cmp)
                cmp.destroy();
            //components.push(cmp);
        });


    });
    tab.sWin = win;
    setTimeout(function () {
        maintab.setActiveTab(tab);
    }, 250);
};
var lookup = {};
var loadExample = function (href, id, title, raw) {
    var tab = Ext.get(id),
        lObj = lookup[href];

    if (id == "-") {
        App.direct.GetHashCode(href, {
            success: function (result) {
                loadExample(href, result.oid, result.title, result);
            }
        });

        return;
    }

    lookup[href] = id;

    if (tab) {
        Ext.get('ExampleTabs').setActiveTab(tab);
    } else {
        if (Ext.isEmpty(title)) {
            var m = /(\w+)\/$/g.exec(href);
            title = m == null ? "[No name]" : m[1];
        }

        title = title.replace(/<span>&nbsp;<\/span>/g, "");
        title = title.replace(/_/g, " ");
        makeTab(id, href, title, raw);
    }
};

var onItemClick = function (record, e) {
    loadExample(record.data.href, record.data.oid, record.data.title, record.data);
};


